﻿using Orleans;
using Orleans.Providers;
using Orleans.Runtime;
using Orleans.Storage;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Sample.Implements
{
    public class UserServiceStorgeProvider : IGrainStorage, ILifecycleParticipant<ISiloLifecycle>
    {

        private Task Init(CancellationToken cancellation)
        {
            Console.WriteLine("UserServiceStorgeProvider Init");

            return Task.CompletedTask;
        }

        /// <summary>
        /// 创建时执行
        /// </summary>
        /// <param name="grainType"></param>
        /// <param name="grainReference"></param>
        /// <param name="grainState"></param>
        /// <returns></returns>
        public Task ReadStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
        {
            var goodsNo = grainReference.GetPrimaryKeyLong();

            grainState.State = new UserServiceState() { MyState = (int)goodsNo };
            Console.WriteLine("UserServiceStorgeProvider ReadStateAsync");

            return Task.CompletedTask;
        }

        public Task WriteStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
        {
            var model = grainState.State as UserServiceState;
            // Save
            Console.WriteLine("UserServiceStorgeProvider WriteStateAsync");
            return Task.CompletedTask;
        }

        public Task ClearStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
        {
            Console.WriteLine("UserServiceStorgeProvider ClearStateAsync");
            return Task.CompletedTask;
        }

        public void Participate(ISiloLifecycle lifecycle)
        {
            Console.WriteLine("UserServiceStorgeProvider Participate");
            lifecycle.Subscribe<UserServiceStorgeProvider>(ServiceLifecycleStage.ApplicationServices, Init);
        }

    }
}
